<template>
	<view>
		<h1>用户聊天姐界面</h1>
		<input class="inputBox" type="text" v-model="chatValue" placeholder="请输入要发送的消息" />
		<button @click="sendChat">发送聊天</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				chatList: [], //聊天内容列表
				chatValue: '', //发送聊天内容
				isSocketOpen: false, //socket是否打开
				pingpangTimes: null, //socket心跳计时器
			}
		},
		onLoad() {
			let requestData = {
				action: 1,
				chatMsg: {
					msg: this.chatValue,
					msgId: null,
					receiverId: null,
					senderId: "22222222" //传送消息者id
				},
				extand: null
			}
			requestData = JSON.stringify(requestData)
			uni.connectSocket({
				url: "ws://101.43.195.96:8809/ws",
				data:requestData,
				success: res => {
					console.log("连接成功", res)
				}
			})
			//监听socket打开
			uni.onSocketOpen(() => {
				this.isSocketOpen = true
				console.log('WebSocket连接已打开！');
			})
			//监听socket关闭
			uni.onSocketClose(() => {
				this.isSocketOpen = false
				console.log('WebSocket连接已关闭！');
			})
			//监听socket错误
			uni.onSocketError(() => {
				this.isSocketOpen = false
				console.log('WebSocket连接打开失败');
			})
			//监听socket消息
			uni.onSocketMessage((res) => {
				console.log("接受到的消息",res)
				let infos = JSON.parse(res.data)
				console.log(infos)
			})
			//先确保清除了之前的心跳定时器
			clearInterval(this.pingpangTimes)
			//每过一段时间发送一次心跳，发送Ping,服务器会反馈pong，这样操作以保持socket一直是连接状态，防止断开连接，心跳停止
			this.pingpangTimes = setInterval(() => {
				let requestData = {
					action: 4,
					chatMsg: {
						msg: null,
						msgId: null,
						receiverId: null,
						senderId: "22222222" //传送消息者id
					},
					extand: null
				}
				requestData = JSON.stringify(requestData)
				uni.sendSocketMessage({
					data: requestData,
					success: () => {
						console.log("心跳执行，处于连接中")
					},
					fail: () => {
						console.log("心跳执行，未处于连接")
						this.isSocketOpen = false
					}
				});
			}, 1000)
		},
		beforeDestroy() {
			clearInterval(this.pingpangTimes) //清除socket心跳定时器
			uni.closeSocket() //关闭socket
		},
		methods: {
			sendChat() {
				let requestData = {
					action: 2,
					chatMsg: {
						msg: this.chatValue,
						msgId: null,
						receiverId: "4124124",
						senderId: "22222222" //传送消息者id
					},
					extand: null
				}
				console.log(requestData)
				requestData = JSON.stringify(requestData)
				console.log(requestData)
				uni.sendSocketMessage({
					data: requestData,
					success: res => {
						console.log("发送成功")
					},
					fail: error => {
						console.log("发送失败")
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.inputBox {
		width: 80%;
		margin: 20px auto;
		border: 1px solid blue;
	}
</style>
